package blackjack.server;

import java.util.Iterator;

/**
 * Message sender
 *
 */
class Broadcaster extends Thread {

	private ActiveSessions activeSessions;
	private OutboundMessages outQueue;

	Broadcaster(ActiveSessions as, OutboundMessages o) {
		activeSessions = as;
		outQueue = o;
		start();
	}

	@SuppressWarnings("unchecked")
	public void run() {
		while (true) {
			String s = outQueue.getMessage(); // blocked
			synchronized (activeSessions) { // activeSessions = lock
				Iterator active = activeSessions.iterator();
				while (active.hasNext()) {
					ClientSession cs = (ClientSession) active.next();
					if (!cs.isAlive()) active.remove();
					else cs.sendMessage(s);
				}
			}
		}
	}

}
